<template>
  <div>
    <!-- 抽屉组件 -->
    <!-- <a-modal
      width="1000px"
      :title="$t('all.autotext1324')"
      :visible="uploadFileVisible"
      :footer="null"
      @cancel="closeUpload"
    > -->
    <div class="upload-wrap">
      <a-descriptions v-if="!title" :title="$t('all.autotext1689')"></a-descriptions>
      <!-- <slot name="title"> -->
      <p>{{ $t('all.autotext1680') }}:</p>
      <ul style="list-style:disc;margin-left:0">
        <li>{{ $t('all.autotext1681') }}</li>
        <li>{{ $t('all.autotext1682') }}</li>
        <li>{{ $t('all.autotext1683') }}</li>
      </ul>
      <a-space>
        <!-- <a-upload
          ref="import"
          name="file"
          accept=".pdf, .jpg, .jpeg, .png"
          :multiple="true"
          :before-upload="beforeUploadSite"
          :customRequest="e => handleUpload(e, 4)"
          :showUploadList="false"
        >
          <a-button type="primary" :loading="medicalUploading">
            <a-icon type="upload" />
            {{ $t('all.autotext1807') }}
          </a-button>
        </a-upload> -->
        <a-upload
          ref="import"
          name="file"
          accept=".pdf, .jpg, .jpeg, .png"
          :multiple="true"
          :before-upload="beforeUploadSite"
          :customRequest="e => handleUpload(e,3)"
          :showUploadList="false"
        >
          <!-- <a-button style="margin-bottom: 10px" :loading="currentTarget.loading" :disabled="currentTarget.btnSwitch"><a-icon type="upload" v-if="!currentTarget.loading" />上传</a-button> -->
          <a-button type="primary" :loading="taxInvoiceUploading">
            <a-icon type="upload" />
            {{ $t('all.autotext1698') }}
          </a-button>
        </a-upload>
        <a-upload
          ref="import"
          name="file"
          accept=".pdf, .jpg, .jpeg, .png"
          :multiple="true"
          :before-upload="beforeUploadSiteOther"
          :customRequest="e => handleUpload(e, 2)"
          :showUploadList="false"
        >
          <!-- <a-button style="margin-bottom: 10px" :loading="currentTarget.loading" :disabled="currentTarget.btnSwitch"><a-icon type="upload" v-if="!currentTarget.loading" />上传</a-button> -->
          <a-button type="primary" :loading="otherUploading">
            <a-icon type="upload" />
            {{ $t('all.autotext1699') }}
          </a-button>
        </a-upload>
        <!-- <a-popconfirm :title="$t('all.autotext14') + '？'" @confirm="clearAll">
          <a-button style="margin-left: 10px" type="danger">{{ $t('all.autotext1473') }}</a-button>
        </a-popconfirm> -->
        <!-- <a-checkbox class="checkbox--right" v-model="autoDesensitizationCheck" :disabled="uploading">{{ $t('all.autotext1690') }}</a-checkbox> -->
      </a-space>
      <!-- </slot> -->
      <div class="bg-img pdf-list"></div>
      <a-table
        :data-source="dataInfo.fileList"
        :rowKey="record => record.uniqueId"
        :pagination="false"
        style="margin-top: 10px;"
      >
        <a-table-column :title="$t('all.autotext334')" data-index="order" width="60px">
          <template slot-scope="text,record,index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1706')" data-index="fileType" width="100px">
          <template slot-scope="text,record">{{ { 1: $t('all.autotext1700'), 2: $t('all.autotext1701'), 3: $t('all.autotext1825'), 4: $t('all.autotext1825')}[record.fileType]  }}</template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext215')" data-index="originalFile">
          <template slot-scope="text,record"><a @click="preview(record.fileUrl)">{{ record.fileName }}</a></template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext582')" data-index="afterFile">
          <template slot-scope="text,record">
            <div class="afterfile">
              <template v-if="desensePassed(record)">
                <a class="filename" @click="preview(record.afterFileUrl)">{{ record.fileName }}</a>
                <!-- <a @click="editFile(record, index)">{{ $t('all.autotext1231') }}</a> -->
              </template>
              <template v-else>
                <span class="grey" v-if="record.afterFileUrl">{{ $t('all.autotext881') }}</span>
                <!-- <a @click="editFile(record, index, 2)">{{ $t('all.autotext236') }}</a> -->
              </template>
            </div>
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext175')" data-index="status" width="500px">
          <template slot-scope="text,record">
            <a-steps :current="record.currentIndex" size="small" :status="record.currentStatus">
              <a-step  v-if="[3,4].includes(record.fileType) ">
                <template slot="title">
                  <a-popover v-if="record.currentStatus === 'error' && record.currentIndex === 0">
                    <template slot="content">
                      <span>{{ record.verifyMsg || '' }}</span>
                    </template>
                    <span>{{ $t('all.autotext1811') }}</span>
                  </a-popover>
                  <span v-else>{{ $t('all.autotext1811') }}</span>
                </template>
              </a-step>
              <a-step v-if="[3,4].includes(record.fileType) " >
                <template slot="title">
                  <a-popover v-if="record.currentStatus === 'error' && record.currentIndex === 1">
                    <template slot="content">
                      <span>{{ record.verifyMsg || '' }}</span>
                    </template>
                    <span>{{ $t('all.autotext1812') }}</span>
                  </a-popover>
                  <span v-else>{{ $t('all.autotext1812') }}</span>
                </template>
              </a-step>
              <!-- <a-step v-if="[3].includes(record.fileType) " >
                <template slot="title">
                  <a-popover v-if="record.currentStatus === 'error' && record.currentIndex === 2">
                    <template slot="content">
                      <span>{{ record.verifyMsg || '' }}</span>
                    </template>
                    <span>{{ $t('all.autotext1814') }}</span>
                  </a-popover>
                  <span v-else>{{ $t('all.autotext1814') }}</span>
                </template>
              </a-step> -->
              <a-step v-if="[3,4].includes(record.fileType) " >
                <template slot="title">
                  <a-popover v-if="record.currentStatus === 'error' && (record.currentIndex === 2 || record.currentIndex === 3)">
                    <template slot="content">
                      <span>{{ record.verifyMsg || '' }}</span>
                    </template>
                    <span>{{ $t('all.autotext1813') }}</span>
                  </a-popover>
                  <span v-else>{{ $t('all.autotext1813') }}</span>
                </template>
              </a-step>
              <a-step :title="$t('all.autotext101')" v-if="record.fileType === 2"/>
            </a-steps>
          </template>
        </a-table-column>
        <a-table-column
          :title="$t('all.autotext187')"
          data-index="operate"
          align="center"
          width="260px"
        >
          <template slot-scope="text,record, index">
            <template v-if="desensePassed(record)">
              <!-- 调整 -->
              <a @click="editFile(record, index)">{{ $t('all.autotext1231') }}</a>
              <a-divider type="vertical" />
              <!-- 还原脱敏 -->
              <a @click="resetFile(record, index)">{{ $t('all.autotext1691') }}</a>
              <a-divider type="vertical" />
            </template>
            <template v-if="[6].includes(record.fileStatus) || ([7].includes(record.fileStatus) && !record.afterFileUrl) || ([2].includes(record.fileType) && !record.afterFileUrl)">
              <!-- 手动脱敏 -->
              <a @click="editFile(record, index, 2)">{{ $t('all.autotext236') }}</a>
              <a-divider type="vertical" />
            </template>
            <template v-if="[0,2,4,6].includes(record.fileStatus) || [1].includes(record.fileType)">
              <!-- 重新上传, 失败状态或者历史文件类型为1的，新版已不存在该类型 -->
              <a-upload
                ref="import"
                name="file"
                accept=".pdf, .jpg, .jpeg, .png"
                :multiple="false"
                :before-upload="beforeUploadSite"
                :customRequest="e => handleUpload(e,record.fileType, index, record)"
                :showUploadList="false"
              >
                <a-button style="padding: 0;" type="link" :loading="record.reUploading"> {{ $t('all.autotext1817') }} </a-button>
                <a-divider type="vertical" />
              </a-upload>
            </template>
            <!-- 查看重复 -->
            <template v-if="[1, 2].includes(record.fileStatus)">
              <a @click="viewRepeatReason(record)">{{ $t('all.autotext1818') }}</a>
              <a-divider type="vertical" />
            </template>
            <!-- 预览 -->
            <template v-if="[6, 7].includes(record.fileStatus) || [2].includes(record.fileType)">
              <a @click="clickViewFile(record)">{{ $t('all.autotext84') }}</a>
              <a-divider v-if="record?.feeApplyDtoStatus !== 20" type="vertical" />
            </template>
            <a-popconfirm :title="$t('all.autotext688')" @confirm="deleteFile(record)" v-if="record?.feeApplyDtoStatus !== 20">
              <!-- 删除 -->
              <a class="table-operator__btn--danger">{{ $t('all.autotext379') }}</a>
            </a-popconfirm>
          </template>
        </a-table-column>
      </a-table>
    </div>
    <!-- </a-modal> -->
    <!-- 图片预览 -->
    <a-modal
      width="50%"
      :visible="imgVisible"
      :footer="null"
      @cancel="imgVisible = false,itemFileUrl=''"
    >
      <div class="image">
        <viewer>
          <img :src="itemFileUrl | dealImageUrl" />
        </viewer>
      </div>
    </a-modal>
    <DesensitizationModal
      ref="desensitization"
      v-bind="{...desensDialog}"
      @ok="handleDesensDialogOk"
      @cancel="handleDesensDialogCancel"
    />
    <a-modal
      width="30%"
      :visible="repeatModal.show"
      :title="$t('all.autotext730')"
      :footer="null"
      @cancel="repeatModal.show = false"
    >
      <div>
        <div style="margin-bottom: 10px">
          <!-- 与其他申请单重复 -->
          <span>{{ $t('all.autotext1708') }}</span> :
          <a :href="repeatModal.repetFullFileUrl" target="_blank">{{ repeatModal.repetFileName }}</a>
        </div>
        <div style="margin-bottom: 10px">
          <!-- 已使用申请单 -->
          <span>{{ $t('all.autotext1703') }}</span> :
          <span>{{ repeatModal.repetApplyNo }}</span>
        </div>
        <div style="margin-bottom: 10px">
          <!-- 提交时间 -->
          <span>{{ $t('all.autotext1704') }}</span> :
          <span>{{ repeatModal.createTimeStr }}</span>
        </div>
      </div>
    </a-modal>
    <!-- <Pdftoimage ref="pdftoimage" @fileAdd="fileAdd"></Pdftoimage> -->
  </div>
</template>

<script>
// import Pdftoimage from '@/components/Pdftoimage/pdftoimage'
import { uploadAndReturnPng, uploadReturnHash, getRepetInfo } from '@/api/common'
import { uploadInvoice } from '@api/cost/cost'
import DesensitizationModal from './components/desensitizationModal.vue'
import moment from 'moment'

export default {
  components: { DesensitizationModal },
  props: {
    title: {
      type: String,
      default: ''
    },
    currentTarget: {
      type: Object,
      default: () => {
        return {}
      }
    },
    uploadFileVisible: {
      type: Boolean,
      default: false
    },
    formList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  inject: {
    getStoreAndSubmitButtonState: {
      type: Function,
      default: () => {}
    }
  },
  data () {
    return {
      dataInfo: {},
      imgVisible: false,
      itemFileUrl: '',
      medicalUploading: false,
      taxInvoiceUploading: false,
      otherUploading: false,
      autoDesensitizationCheck: true,
      desensDialog: {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      },
      listLength: 0,
      listFlag: 0,
      currentUploadLoading: 0,
      repeatModal: {
        show: false
      }
    }
  },
  methods: {
    backFileList (val) {
      // this.dataInfo.fileList = val
      this.$set(this.dataInfo, 'fileList', this.fileStatusFilter(val))
    },
    // 赋值
    copyData (data) {
      data.fileList = this.fileStatusFilter(data.fileList)
      this.dataInfo = data
    },
    fileStatusFilter (fileList) {
      /**
       * fileStatus 状态 0识别失败（腾讯OCR无法识别） 1识别成功  2查重失败（存在重复）3无重复  4增值税为假（腾讯OCR识别为假）5增值税为真  6脱敏失败  7完成(脱敏成功)
       * fileType  1、3发票、票据， 2是其他，4废弃了
       **/
      return fileList.map(item => {
        const newItem = { ...item }
        if (item.fileType === 2) {
          newItem.currentIndex = 0
          newItem.currentStatus = 'finish'
        } else if (item.fileType === 3 || item.fileType === 4) {
          if ([0, 1].includes(item.fileStatus)) {
            item.fileStatus === 0 && (newItem.currentStatus = 'error')
            item.fileStatus === 1 && (newItem.currentStatus = 'process')
            newItem.currentIndex = 0
          } else if ([2, 3].includes(item.fileStatus)) {
            item.fileStatus === 2 && (newItem.currentStatus = 'error')
            item.fileStatus === 3 && (newItem.currentStatus = 'process')
            newItem.currentIndex = 1
          } else if ([4, 5].includes(item.fileStatus) && item.fileType === 3) {
            item.fileStatus === 4 && (newItem.currentStatus = 'error')
            item.fileStatus === 5 && (newItem.currentStatus = 'process')
            newItem.currentIndex = 2
          } else if ([6, 7].includes(item.fileStatus)) {
            item.fileStatus === 6 && (newItem.currentStatus = 'error')
            item.fileStatus === 7 && (newItem.currentStatus = 'finish')
            newItem.currentIndex = 2
          }
        }
        return newItem
      })
    },
    // 切换条目再打开弹窗时重置部分初始值
    resetData () {
      this.autoDesensitizationCheck = true
    },
    beforeUploadSite (file, fileList) {
      const list = fileList.slice(0, 5)
      if (list.some(item => item.uid === file.uid)) {
        const formatImg = /((gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
        const formatPdf = /(pdf|PDF)$/i
        const isLt1M = file.size / 1024 / 1024 < 1

        if (!isLt1M) {
          this.$message.error(this.$t('all.autotext1783'))
          return false
        }
        if (formatImg.test(file.type) || formatPdf.test(file.type)) {
          return true
        } else {
          this.$message.error(this.$t('all.autotext293'))
          return false
        }
      } else {
        this.$message.error(this.$t('all.autotext1785'))
        return false
      }
    },
    beforeUploadSiteOther (file, fileList) {
      const list = fileList.slice(0, 3)
      if (list.some(item => item.uid === file.uid)) {
        const formatImg = /((gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
        const formatPdf = /(pdf)$/i
        const isLt5M = file.size / 1024 / 1024 < 5

        if (!isLt5M) {
          this.$message.error(this.$t('all.autotext1784'))
          return false
        }
        if (formatImg.test(file.type) || formatPdf.test(file.type)) {
          return true
        } else {
          this.$message.error(this.$t('all.autotext293'))
          return false
        }
      } else {
        this.$message.error(this.$t('all.autotext1786'))
        return false
      }
    },
    viewRepeatReason (record) {
      getRepetInfo({ id: record.id }).then(res => {
        this.repeatModal = {
          show: true,
          ...res,
          createTimeStr: res.createTime ? moment(res.createTime).format('YYYY-MM-DD') : '-',
          repetFullFileUrl: `${this.$minio}${res.repetFileUrl}`,
          repetApplyNo: res.repetApplyNo || this.$t('all.autotext1821')
        }
      })
    },
    // 修改上传
    async handleUpload ({ file }, flag, index, record_) {
      // flag：2 其他 3 增值税发票 4 医疗票据
      const fileIds = []
      if (this.dataInfo.fileList) {
        if (this.dataInfo.fileList.some(item => item.fileName === file.name) && index === undefined) {
          this.$message.error(this.$t('all.autotext1705'))
          return
        }
        this.dataInfo.fileList.forEach(item => {
          if (record_?.id !== item.id) {
            fileIds.push(item.id)
          }
        })
      }

      this.currentUploadLoading++

      index === undefined && this.listLength++
      // 校验格式
      // this.uploading = true
      const isPdfFormat = /pdf$/i.test(file.type)

      let request = ''
      const proId = localStorage.getItem('CURRENT_PROID')
      if ([1, 3, 4].includes(flag)) {
        request = uploadInvoice
        this.medicalUploading = flag === 4 && index === undefined
        this.taxInvoiceUploading = flag === 3 && index === undefined
      } else if ([2].includes(flag)) {
        request = uploadAndReturnPng
        this.otherUploading = flag === 2
      }
      this.getStoreAndSubmitButtonState && this.getStoreAndSubmitButtonState(true)

      const info = {}
      // 将上传的文件进行展示
      info.fileName = file.name
      info.uniqueId = Math.random().toString().substr(2, 10)
      info.fileHash = ''
      if (isPdfFormat) {
        const params = new FormData()
        params.append('file', file)
        const res = await uploadReturnHash(params)
        info.url = res.url
        info.fileHash = res.fileHash
      }
      const params = new FormData()
      params.append('file', file)
      params.append('proId', proId ? Number(proId) : null)
      params.append('fileIds', fileIds.join(','))
      if ([1, 3, 4].includes(flag)) {
        params.append('uploadType', flag === 1 ? 3 : flag)
      }
      if (index !== undefined) {
        this.dataInfo.fileList[index].reUploading = true
      }
      this.$forceUpdate()
      request(params).then(res => {
        info.id = res.id
        info.repetFileId = res.repetFileId
        if ([1, 3, 4].includes(flag)) {
          info.fileType = res.fileType
          info.fileUrl = res.url
          info.afterFileUrl = res.afterUrl
          info.fileStatus = res.fileStatus
          info.verifyMsg = res.verifyMsg
        } else if ([2].includes(flag)) {
          info.fileType = 2
          info.fileUrl = res
          info.fileStatus = 100
        }
        info.fileHash = info.fileHash ? info.fileHash : (res.fileHash || '')
        // 上传后保存文件服务器地址到本地
        if (this.dataInfo.fileList) {
          if (index !== undefined) {
            info.reUploading = false
            this.dataInfo.fileList[index] = info
          } else this.dataInfo.fileList.push(info)
        } else {
          this.dataInfo.fileList = []
          this.dataInfo.fileList.push(info)
        }
        this.dataInfo.fileList = this.fileStatusFilter(this.dataInfo.fileList)
        this.$emit('uploadFile', this.dataInfo.fileList)
      }).catch(() => {
      }).finally(() => {
        if (this.currentUploadLoading !== 0) {
          this.currentUploadLoading--
        }
        if (flag === 4 && this.currentUploadLoading === 0) this.medicalUploading = false
        if (flag === 3 && this.currentUploadLoading === 0) this.taxInvoiceUploading = false
        if (flag === 2 && this.currentUploadLoading === 0) this.otherUploading = false
        this.listFlag++
        if (this.listFlag === this.listLength) {
          this.uploading = false
          this.listFlag = 0
          this.listLength = 0
        }
        this.$forceUpdate()
        this.currentUploadLoading === 0 && this.getStoreAndSubmitButtonState && this.getStoreAndSubmitButtonState(false)
      })
    },
    // 关闭弹窗
    // closeUpload () {
    //   this.$emit('closeUpload', this.dataInfo)
    // },
    /**
     * 设置脱敏弹窗的文件
     * @param fileUrl 原始文件 半路径
     * @param afterFileUrl 脱敏后文件 半路径
     */
    setDenseModalFile (fileUrl, afterFileUrl) {
      this.desensDialog.originalFileUrl = this.$options.filters.dealImageUrl(fileUrl)
      this.desensDialog.afterFileUrl = this.$options.filters.dealImageUrl(afterFileUrl)
      this.desensDialog.fileType = fileUrl?.toLowerCase().endsWith('.pdf') ? 2 : 1
    },
    // 对比预览
    clickViewFile ({ fileUrl, afterFileUrl }) {
      this.setDenseModalFile(fileUrl, afterFileUrl)
      this.desensDialog.visible = true
      this.desensDialog.type = 'preview'
    },
    // 单文件预览
    preview (fileUrl) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(fileUrl)) {
        this.itemFileUrl = fileUrl
        this.imgVisible = true
      } else {
        // 打开空白页 展示文件
        const fullFileUrl = this.$options.filters.dealImageUrl(fileUrl)
        window.open(fullFileUrl, '_blank')
      }
    },
    // 点击删除上传的文件
    deleteFile (row) {
      let flag = false
      this.formList.forEach(item => {
        if (item.editable) {
          flag = 2
          return
        }
        if (item.fileList.some(e => e.fileName === row.fileName)) {
          flag = 1
        }
      })
      if (flag === 2) {
        this.$message.error(this.$t('all.autotext1293'))
        return
      }
      if (flag === 1) {
        this.$message.error(this.$t('all.autotext1707'))
        return
      }
      const newList = this.dataInfo.fileList.filter(item => item.uniqueId !== row.uniqueId)
      this.dataInfo.fileList = newList
      this.$forceUpdate()
      this.$emit('uploadFile', this.dataInfo.fileList)
    },
    /**
     * 调整文件
     * @param afterFileUrl
     * @param fileName
     * @param fileUrl
     * @param index
     * @param type 调整还是手动脱敏 1-调整 2-手动脱敏
     */
    editFile ({ afterFileUrl, fileName, fileUrl }, index, type = 1) {
      this.desensDialog.type = 'edit'
      this.desensDialog.selectRowIndex = index
      this.setDenseModalFile(fileUrl, type === 2 ? fileUrl : afterFileUrl)
      this.desensDialog.fileName = fileName
      this.desensDialog.visible = true
      this.$nextTick(() => {
        this.$refs.desensitization.init()
      })
    },
    // 还原文件
    resetFile (record, index) {
      const selectRow = this.dataInfo.fileList[index]
      if (selectRow) {
        this.$set(selectRow, 'afterFileUrl', '')
      }
      this.$emit('uploadFile', this.dataInfo.fileList)
      this.editFile(record, index, 2)
    },
    /**
     * @function 手动脱敏
     */
    desensitization () {
      this.desensDialog.visible = true
    },
    // 清空全部
    clearAll () {
      this.dataInfo.fileList = []
      this.$forceUpdate()
    },
    handleDesensDialogOk (fileUrl) {
      const selectRow = this.dataInfo.fileList[this.desensDialog.selectRowIndex]
      if (selectRow) {
        this.$set(selectRow, 'afterFileUrl', fileUrl)
        this.$set(selectRow, 'fileStatus', 7) // 脱敏完成后，标记为已脱敏
        this.dataInfo.fileList = this.fileStatusFilter(this.dataInfo.fileList)
      }
      this.$emit('uploadFile', this.dataInfo.fileList)
    },
    handleDesensDialogCancel () {
      this.desensDialog = {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      }
    },
    // 脱敏通过
    desensePassed ({ fileUrl, afterFileUrl }) {
      return afterFileUrl && afterFileUrl !== fileUrl
    }
  }
}
</script>
<style scoped lang="less">
.upload-wrap {
  width: 100%;
  padding: 24px 0;
}
.checkbox--right {
  // float: right;
  // line-height: 32px;
  margin-left: 30px;
}
.ant-modal-body {
  .ant-table-tbody {
    td {
      .afterfile {
        width: 200px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .table-operator__btn--danger {
        color: #F02F2F;
      }
      .grey {
        color: #999999;
      }
    }
  }
}
.image {
  img {
    display: block;
    width: 80%;
    margin: 10px auto;
  }
}
.file-icon {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-right: 10px;
}

.bg-img {
    width: 100%;
    margin-top: 20px;
    position: fixed;
    left: -10000px;

    /deep/ .canvas {
        cursor: pointer;
    }
}
</style>
